package command;


import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Comparator;
import java.util.List;

import comparetor.BirthdayComparator;
import comparetor.IdComparator;
import pojo.Command;
import pojo.Customer;
import processor.impl.DataProcessorImpl;

public class ParseCommandImpl implements ParseCommand{
	private String cmd;
	private List<Customer> cl;
	private Comparator<Customer> compr;
	private DataOutputStream out1;
	private StringBuilder sb;

	

	public ParseCommandImpl(List<Customer> cl,DataOutputStream out1){
		this.cl=cl;
		this.out1=out1;
	}
	
	public String getCmd() {
		return cmd;
	}
	public void setCmd(String cmd) {
		this.cmd = cmd;
	}
	public boolean command(String cmd) {
		this.cmd=cmd;
		Command result;
//		System.out.println(cmd.matches("^(C|L)\\s((xml)|(line))\\s((id)|(birth))$"));
		if(cmd.matches("^(C|L)\\s((xml)|(line))\\s((id)|(birth))$")){
			result=new Command(cmd);
//			System.out.println(result.getC1()+"..."+result.getC2()+"..."+result.getC3());
			if(result.getC3().equals("id")){
				compr=new IdComparator();
			}else{
				compr=new BirthdayComparator();			
			}
			if(result.getC2().equals("xml")){//
				sb=new DataProcessorImpl(cl, "xml").process(compr);
			}else{
				sb=new DataProcessorImpl(cl, "line").process(compr);
			}
			if(result.getC1().equals("C")){
				
				try {
					FileOutputStream out = new FileOutputStream("Ziv.txt");
					out.write(sb.toString().getBytes());
					out1.writeChars("Succeed!!!\n");
					return true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				try {
					out1.writeChars(sb.toString());
					return true;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		else if(cmd.matches("Q")){
			return false;
		}
		else{
			try {
				out1.writeChars("no such command!!!\n");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		return false;
		
	}

}
